package fuzion24.device.vulnerability.vulnerabilities.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Base64;

import java.io.File;
import java.security.MessageDigest;
import java.util.HashSet;
import java.util.Scanner;

import fuzion24.device.vulnerability.util.SharedPreferencesUtils;

/**
 * Created by fuzion24 on 12/4/15.
 */
public class DeviceUpdateChecker {
    private DeviceUpdateChecker() {
    }

    public static boolean wasDeviceUpdated(Context ctx){

        /*
            Take a hash of the build.prop and /proc/version
            If this changes, assume the device has been updated
        */
        String buildPropFile = readFile("/system/build.prop");
        String procVersion   = readFile("/proc/version");

        String fingerprint = hashString(buildPropFile + procVersion);
        String lastFingerprint = SharedPreferencesUtils.getBuildUpdateFingerprint(ctx);
        if(fingerprint.equals(lastFingerprint)){
            return false;
        } else {
            SharedPreferencesUtils.setBuildUpdateFingerPrint(ctx, fingerprint);
            return true;
        }
    }

    private static String hashString(String data){
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(data.getBytes());
            byte[] hash = md.digest();
            return Base64.encodeToString(hash, Base64.DEFAULT);
        } catch (Exception e) {
            return "";
        }
    }

    private static String readFile(String filename){
        try {
            return new Scanner(new File(filename)).useDelimiter("\\Z").next();
        }catch(Exception e){
            return "";
        }
    }

}
